package com.yimi.appstore.download2;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;

import android.util.Log;

/**
 * 下载线程类
 * 
 * @author Administrator
 * 
 */
public class DownLoadThread extends Thread {
	private static final String TAG = "DownloadThread";
	private File saveFile;
	private URL downUrl;
	private long block;
	private int BUFFER = 1024 * 8;
	/* 下载开始位置 */
	private int threadId = -1;
	private long downLength;
	private boolean finish = false;
	private DownloadJob downloader;

	/**
	 * @param downloader
	 *            :下载器
	 * @param downUrl
	 *            :下载地址
	 * @param saveFile
	 *            :下载路径
	 * 
	 */
	public DownLoadThread(DownloadJob downloader, URL downUrl, File saveFile, long block, long downLength, int threadId) {
		this.downUrl = downUrl;
		this.saveFile = saveFile;
		this.block = block;
		this.downloader = downloader;
		this.threadId = threadId;
		this.downLength = downLength;
	}

	HttpURLConnection http;

	@Override
	public void run() {
		if (downLength < block) {// 未下载完成
			try {
				print("Thread " + this.threadId + " download start");
				// 使用Get方式下载
				http = (HttpURLConnection) downUrl.openConnection();
				http.setConnectTimeout(5 * 1000);

				long startPos = block * (threadId - 1) + downLength;// 开始位置
				long endPos = block * threadId - 1;// 结束位置
				http.setRequestProperty("RANGE", "bytes=" + startPos + "-" + endPos);// 设置获取实体数据的范围
				InputStream inStream = http.getInputStream();
				byte[] buffer = new byte[BUFFER];
				int offset = 0;
				print("url>>"+downUrl+"Thread " + this.threadId + " start download from position " + startPos);
				RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");
				threadfile.seek(startPos);

				while ((offset = inStream.read(buffer, 0, BUFFER)) != -1) {
					threadfile.write(buffer, 0, offset);
					downLength += offset;
					downloader.append(offset);
				}

				threadfile.close();
				inStream.close();
				print("Thread " + this.threadId + " download finish");
				downloader.update(this.threadId, downLength);
				this.finish = true;
			} catch (SocketException e) {
				downloader.setNotFinish(false);
				downloader.update(this.threadId, downLength);
				if(e.toString().contains("timed out")){
					downloader.notifyStatus(DownloadManager.STATE_ERROR);
				}
				print("Thread " + this.threadId + ":" + e+">downLength:"+downLength);
			} catch (IOException e) {
				downloader.setNotFinish(false);
				downloader.update(this.threadId, downLength);
				print("Thread " + this.threadId + ":" + e+">downLength:"+downLength);
			}
		}
	}

	public void cancle() {
		if (http != null)
			http.disconnect();
	}

	/**
	 * 打印日志信息
	 * 
	 * @param msg
	 */
	private static void print(String msg) {
		Log.i(TAG, msg);
	}

	/**
	 * 下载是否完成
	 * 
	 * @return
	 */
	public boolean isFinish() {
		return finish;
	}

	/**
	 * 已经下载的内容大小
	 * 
	 * @return 如果返回值为-1,代表下载失败
	 */
	public long getDownLength() {
		return downLength;
	}
}
